﻿using Renci.SshNet.Sftp;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.IO.Compression;
using Microsoft.Extensions.Hosting;
using AutoMapper.Internal;

namespace NP.BPMReportPlatform.Resume
{
    /// <summary>
    /// ftp操作类
    /// </summary>
    public class FtpTool : IDisposable
    {
        SftpClient? sftpClient = null;
        private string _host = string.Empty;
        private int _post = 8888;

        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="timeout"></param>
        public FtpTool(string host, int port, string username, string password, int timeout = 10)
        {
            _host = host;
            _post = port;
            sftpClient = new SftpClient(host, port, username, password);
            sftpClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(timeout);
            sftpClient.Connect();
        }

        /// <summary>
        /// 得到ftp链接
        /// </summary>
        /// <returns></returns>
        public void UploadFile(Stream input, string path)
        {
            sftpClient?.UploadFile(input, path, true);
        }

        /// <summary>
        /// 获取sftp文件流
        /// </summary>
        /// <returns></returns>
        public (Dictionary<string, string>, List<string>) SftpDownloadFile(string ftpPath, string localPath)
        {
            Dictionary<string, string> replaceFiles = new Dictionary<string, string>();
            List<string> excelNamse = new List<string>();

            using (var remoteFileStream = sftpClient.OpenRead(ftpPath))
            {
                // 创建本地临时文件
                var tempFilePath = localPath + ftpPath;
                var dictionary = System.IO.Path.GetDirectoryName(tempFilePath);
                // 将远程文件流写入本地临时文件
                if (!Directory.Exists(dictionary))
                {
                    // 创建up文件夹
                    Directory.CreateDirectory(dictionary);
                }

                using (FileStream fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
                {
                    remoteFileStream.CopyTo(fileStream);
                }

                if (ftpPath.ToLower().EndsWith(".zip"))
                {
                    // 解压缩 ZIP 文件
                    var result = UnzipFile(tempFilePath, dictionary);

                    result.Item1?.ForAll(item =>
                    {
                        replaceFiles.Add(item.Key, item.Value);
                    });

                    excelNamse.AddRange(result.Item2);

                    // 删除临时文件
                    File.Delete(tempFilePath);
                }
                else
                {
                    replaceFiles.Add(tempFilePath, tempFilePath);
                }

                return (replaceFiles, excelNamse);
            }
        }

        /// <summary>
        /// 删除对应文件
        /// </summary>
        /// <param name="ftpPath"></param>
        public void DeleteSftpFile(string ftpPath)
        {
            sftpClient?.DeleteFile(ftpPath);
        }

        /// <summary>
        /// 得到Sft所有文件
        /// </summary>
        public List<SftpFile> GetSftpAllFile(string sftpPath)
        {
            return sftpClient?.ListDirectory(sftpPath).ToList();
        }

        /// <summary>
        /// 释放
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void Dispose()
        {
            if (sftpClient != null && sftpClient.IsConnected)
            {
                sftpClient?.Dispose();
            }
        }

        private (Dictionary<string, string>, List<string>) UnzipFile(string zipFilePath, string destinationDirectory)
        {
            Dictionary<string, string> replaceFiles = new Dictionary<string, string>();
            List<string> excelNamse = new List<string>();

            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    // 检测文件名中是否含有特殊字符，如果有的话，将该文件重命名，并且记录原文件名和新文件名再解压
                    string cleanFileName = Path.GetInvalidFileNameChars()
                    .Aggregate(entry.FullName, (current, c) => current.Replace(c, '_'));

                    // 如果检测到文件名是excel表格，记录下来，等伙需要解析该文件
                    if (entry.FullName.EndsWith(".xlsx"))
                    {
                        excelNamse.Add(cleanFileName);
                    }

                    string destinationPath = Path.Combine(destinationDirectory, cleanFileName);
                    // 创建目录结构（如果需要）
                    Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                    // 解压文件
                    entry.ExtractToFile(destinationPath, true);

                    if (!entry.FullName.EndsWith(".xlsx"))
                    {
                        replaceFiles.Add(entry.Name, destinationPath);
                    }
                }
            }

            return (replaceFiles, excelNamse);
        }
    }
}
